package com.ysb.hbase.dml;

import com.ysb.hbase.model.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


@Slf4j
public class HbaseDdlService {
    private Configuration configuration;
    private volatile Connection connection;

    public void setConfiguration(Configuration configuration) {
        this.configuration = configuration;
    }

    public HbaseDdlService() {
    }

    public HbaseDdlService(Configuration configuration, Connection connection) {
        this.setConfiguration(configuration);
        this.setConnection(connection);
    }

    public void setConnection(Connection connection) {
        this.connection = connection;
    }

    public Connection getConnection() {
        if (null == this.connection) {
            synchronized (this) {
                if (null == this.connection) {
                    try {
                        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(200, Integer.MAX_VALUE, 60L,
                                TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
                        // init pool
                        poolExecutor.prestartCoreThread();
                        Connection connection = ConnectionFactory.createConnection(configuration, poolExecutor);
                        this.connection = connection;
                    } catch (Exception e) {
                        log.error("hbase connection资源池创建失败", e);
                    }
                }
            }
        }
        return this.connection;
    }
}
